package com.gack.business.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.gack.business.model.BackCode;
import com.gack.business.model.BackLog;
import com.gack.business.model.BackRole;
import com.gack.business.model.BackUser;
import com.gack.business.model.ReturnResult;
import com.gack.business.repository.BackCodeRepository;
import com.gack.business.repository.BackLogRepsitory;
import com.gack.business.repository.BackRoleRepository;
import com.gack.business.repository.BackUserRepository;
import com.gack.helper.common.util.StdRandom;
import com.gack.helper.common.util.StringUtil;





@Service
public class BackUserService {
	
	
	@Autowired
	private BackUserRepository backUserRepository;
	
	@Autowired
	private BackCodeService   backCodeService;
	
	@Autowired
	private BackRoleRepository  backRoleRepository;
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private BackCodeRepository   backCodeRepository;
	
	@Autowired
	private BackLogRepsitory   backLogRepsitory;
	
	@PersistenceContext
	EntityManager em;
	
	//创建账号
	@Transactional
	public ReturnResult insertBackIUser(String userid,String username,String name,String gender,String department,String roleid,
			String storename,String userPhone,String email,Integer status,String storeid) {
		ReturnResult returnResult = new ReturnResult();
		BackUser  operatorUser=new BackUser();
		if (department != null && roleid != null) {
			List<BackUser> operUserList = backUserRepository.findByUsername(username);
			if (operUserList.size() > 0) {
				returnResult.setKey("error");
				returnResult.setValue("账号已存在");
			} else {
				List<BackUser> list = backUserRepository.findByPhone(userPhone);
				if (list.size() > 0) {
					returnResult.setKey("error");
					returnResult.setValue("手机号已存在");
				} else {
					operatorUser.setCreattime(new Date());
					operatorUser.setName(name);
					String pwd = getSixCode();
					operatorUser.setPassword(pwd);
					operatorUser.setStatus(0);
					operatorUser.setUsername(username);
					operatorUser.setPhone(userPhone);
					operatorUser.setDepartment(department);
					operatorUser.setRole(roleid);
					operatorUser.setStoreid(storeid);
					BackRole  backRole=	backRoleRepository.findOne(roleid);
					if(backRole!=null){
						operatorUser.setPids(backRole.getPids());
					}
					operatorUser.setGender(gender);
					operatorUser.setStorename(storename);
					operatorUser.setEmail(email);
					backUserRepository.save(operatorUser);
					try {
						returnResult = backCodeService.sendCodeforAddAccount(name, pwd, userPhone, username);
					} catch (Exception e) {
						e.printStackTrace();
					}
					/***/
					if(userid!=null&&!userid.equals("")){
						BackLog backLog =new BackLog();
						backLog.setOperationdate(new Date());
						backLog.setDetails("添加账号");
						BackUser  backUser=	backUserRepository.findOne(userid);
						if(backUser!=null){
							backLog.setName(backUser.getName());
							if(backUser.getPids().equals("1")&&backUser.getPids()!=null&&!backUser.getPids().equals("")){
								backLog.setStatus("1");
								backLog.setType("后台");
							}else if(backUser.getPids().equals("2")&&backUser.getPids()!=null&&!backUser.getPids().equals("")){
								backLog.setStatus("2");
								backLog.setType("门店");
							}
						}
						backLogRepsitory.save(backLog);
					}
					
					returnResult.setKey("success");
					returnResult.setValue("保存成功");
				}
			}
		} else {
			returnResult.setKey("error");
			returnResult.setValue("请给账号分配部门和角色");
		}
		return returnResult;

	}

	
	//账号详情
	public BackUser queryBackUserinfo(String id) {
		return backUserRepository.findOne(id);
	}
	
	
	/**
	 * 删除一个也可以多个
	 * @param ids
	 *            字符串id
	 * @return
	 */
	@Transactional
	public ReturnResult deleteForOiuser(String ids,String userid) {
		ReturnResult returnResult = new ReturnResult();
		String[] str = StringUtil.StrList(ids);
		List<BackUser> lists = new ArrayList<>();
		String id = "";
		BackUser operatorUser = null;
		for (int i = 0; i < str.length; i++) {
			operatorUser = new BackUser();
			id = str[i];
			operatorUser.setId(id);
			lists.add(operatorUser);
		}
		backUserRepository.delete(lists);
		if(userid!=null&&!userid.equals("")){
			BackLog backLog =new BackLog();
			backLog.setOperationdate(new Date());
			backLog.setDetails("添加账号");
			BackUser  backUser=	backUserRepository.findOne(userid);
			if(backUser!=null){
				backLog.setName(backUser.getName());
				if(backUser.getPids().equals("1")&&backUser.getPids()!=null&&!backUser.getPids().equals("")){
					backLog.setStatus("1");
					backLog.setType("后台");
				}else if(backUser.getPids().equals("2")&&backUser.getPids()!=null&&!backUser.getPids().equals("")){
					backLog.setStatus("2");
					backLog.setType("门店");
				}
			}
			backLogRepsitory.save(backLog);
		}
		returnResult.setKey("success");
		returnResult.setValue("删除成功");
		return returnResult;
	}
	
	
	//编辑账号
	@Transactional
	public ReturnResult  editOiSysuer(String userid,String id,String username,String name,String gender,String department,String roleid,
			String storename,String userPhone,String email,Integer status,String storeid){
		ReturnResult returnResult=new ReturnResult();
		if(roleid!=null&&!roleid.equals("")){
			BackUser backUser=	backUserRepository.findOne(id);
			if(backUser!=null){
					List<BackUser> backusers=backUserRepository.findByUsernameAndIdNot(username,id);
					if(backusers.size()>0&&backusers!=null){
						returnResult.setKey("error");
						returnResult.setValue("账号已存在");
					}else{
						if(userPhone!=null&&!userPhone.equals("")){
							List<BackUser> backusers1=backUserRepository.findByPhoneAndIdNot(userPhone,id);
							if(backusers1.size()>0&&backusers1!=null){
								returnResult.setKey("error");
								returnResult.setValue("手机号已存在");
							}else{
								backUser.setUsername(username);
								backUser.setCreattime(new Date());
								backUser.setDepartment(department);
								backUser.setEmail(email);
								backUser.setName(name);
								backUser.setPhone(userPhone);
								backUser.setRole(roleid);
								backUser.setStoreid(storeid);
								BackRole  backRole=	backRoleRepository.findOne(roleid);
								if(backRole!=null){
									backUser.setPids(backRole.getPids());
								}
								backUser.setStatus(status);
								backUser.setStorename(storename);
								backUser.setGender(gender);
								backUserRepository.save(backUser);
								if(userid!=null&&!userid.equals("")){
									BackLog backLog =new BackLog();
									backLog.setOperationdate(new Date());
									backLog.setDetails("添加账号");
									BackUser  bckUser=	backUserRepository.findOne(userid);
									if(bckUser!=null){
										backLog.setName(bckUser.getName());
										if(bckUser.getPids().equals("1")&&bckUser.getPids()!=null&&!bckUser.getPids().equals("")){
											backLog.setStatus("1");
											backLog.setType("后台");
										}else if(bckUser.getPids().equals("2")&&bckUser.getPids()!=null&&!bckUser.getPids().equals("")){
											backLog.setStatus("2");
											backLog.setType("门店");
										}
									}
									backLogRepsitory.save(backLog);
								}
								
								returnResult.setKey("success");
								returnResult.setValue("修改成功");
							}
						}else{
							returnResult.setKey("error");
							returnResult.setValue("手机号不能为空");
						}
					}
			}else{
				returnResult.setKey("error");
				returnResult.setValue("账号不存在");
			}
			
		}else{
			returnResult.setKey("error");
			returnResult.setValue("请给账号分配角色");
			
		}
		return returnResult;
		
	}
	//账号查询列表
	public Page<BackUser> multiconditioniQuery(Integer page, Integer size, String name, String phone, Integer status
			) {
		Specification<BackUser> specification = new Specification<BackUser>() {
			@Override
			public Predicate toPredicate(Root<BackUser> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				if (name != null && !name.equals("")) {
					lstPredicates.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+name+"%"));
				}
				if (phone != null && !phone.equals("")) {
					lstPredicates.add(criteriaBuilder.like(root.get("phone").as(String.class), "%"+phone+"%"));
				}
				if (status != null) {
					lstPredicates.add(criteriaBuilder.equal(root.get("status"), status));
				}
				
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		Sort sort = new Sort(Sort.Direction.DESC, "creattime");
		Pageable pageable = new PageRequest(page, size, sort);
		Page<BackUser> list = backUserRepository.findAll(specification, pageable);
		if (list.getContent().size() > 0) {
			for (BackUser operatorUser : list.getContent()) {
				if (operatorUser.getRole() != null) {
					BackRole operatorRole = backRoleRepository.findOne(operatorUser.getRole());
					if (operatorRole != null) {
						operatorUser.setRolename(operatorRole.getRolename());
					}
				}
			}
		}
		return list;
	}
	
	
	public  Page<BackRole>  queryRoles(Integer page, Integer size){
		if(page==null){
			page=0;
		}
		if(size==null){
			size=10;
		}
		Sort sort = new Sort(Sort.Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
		return backRoleRepository.findAll(pageable);
	}
	
	
	
	//商务后台登录
	/**
	 * 
	 * @Description: 验证用户名密码 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return ReturnResult    @throws 
	 */
	@Transactional
	public Map<String, Object> validatUandP(String username, String password) {
		Map<String, Object> map = new HashMap<>();
		List<BackUser> operUserList = backUserRepository.findUserByUsername(username);
		if (operUserList != null && operUserList.size() > 0) {
			BackUser operatorUser = operUserList.get(0);
			if (operatorUser.getPassword() != null && (!operatorUser.getPassword().equals(""))) {
				if (operatorUser.getPassword().equals(password)) {
					BackUser operatorUser1 = backUserRepository.operatorLogin(username, password);
					if (operatorUser1 != null) {
						// 登录状态正常
						if (operatorUser.getStatus() == 0) {

							// 登录后分配权限
							if (operatorUser.getRole() != null && !operatorUser.getRole().equals("")) {
								BackRole operatorRole = backRoleRepository.findOne(operatorUser.getRole());
								if (operatorRole != null) {
									String pids = operatorRole.getPids();
									if (!pids.equals("")) {
										map.put("pid", pids);
										map.put("rolename", operatorRole.getRolename());
										map.put("id", operatorUser.getId());
										map.put("iuser", operatorUser);
										map.put("status", 1);
										map.put("storeid", operatorUser.getStoreid());
										request.getSession().setAttribute("isysUser", operatorUser);
									}
								}
							} else {
								map.put("error", "该账号没有权限");
								map.put("status", 2);
							}
							
							//禁用
						} else if (operatorUser.getStatus() == 1) {
							map.put("error", "该账号禁用");
							map.put("status", 3);
							
						} 
					}
				} else {
					map.put("error", "密码错误");
					map.put("status", 6);
					
				}
			} else {
				map.put("error", "密码错误");
				map.put("status", 6);
				
			}

		} else {
			map.put("error", "请联系管理员，创建账号");
			map.put("status", 7);
		}

		return map;
	}
	
	
	/**
	 * 
	 * @param telephone
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public ReturnResult sendVeryMessage(String account) throws Exception {
		ReturnResult returnResult = new ReturnResult();
		List<BackUser> operUserList = backUserRepository.findUserByUsername(account);
		if (operUserList.size() > 0) {
			if (operUserList.get(0).getPhone() != null && operUserList.get(0).getName() != null) {
				returnResult = backCodeService.sendCode(operUserList.get(0).getName(),
						operUserList.get(0).getPhone());
			} else {
				if(operUserList.get(0).getUsername().equals("admin")){
					returnResult.setKey("202");
					returnResult.setValue("您是超级管理员,想修改新密码,请到账号设置中编辑手机号和姓名!");
				}else{
					returnResult.setKey("201");
					returnResult.setValue("名字手机号为空");
				}
			}
		} else {
				returnResult.setKey("203");
				returnResult.setValue("用户不存在");
		}
		return returnResult;
	}
	
	/**
	 * 
	 * @param telephone
	 * @param password
	 * @return
	 */
	@Transactional
	public ReturnResult forgetPassword(String username, String password) {
		ReturnResult returnResult = new ReturnResult();
		List<BackUser> operUserList = backUserRepository.findUserByUsername(username);
		BackUser operatorUser = null;
		if (operUserList.size() > 0) {
			operatorUser = operUserList.get(0);
			operatorUser.setPassword(password);
			backUserRepository.save(operatorUser);
			returnResult.setKey("success");
			returnResult.setValue("设置密码成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("用户不存在");
		}
		return returnResult;

	}
	
	public ReturnResult validateUsernameIs(String username) {

		ReturnResult returnResult = new ReturnResult();
		List<BackUser> operUserList = backUserRepository.findUserByUsername(username);
		if (operUserList.size() == 0) {
			returnResult.setKey("error");
			returnResult.setValue("用户不存在");
		} else {
			returnResult.setKey("success");
			returnResult.setValue("验证成功");
		}
		return returnResult;

	}
	
	public ReturnResult vlidateCodeIsexist(String username, String code) {
		ReturnResult returnResult = new ReturnResult();
		List<BackUser> operUserList = backUserRepository.findUserByUsername(username);
		if (operUserList.size() > 0) {
			List<BackCode> list = backCodeRepository.findCodeByPhone(operUserList.get(0).getPhone());
			if (list == null || list.size() == 0) {
				returnResult.setKey("error");
				returnResult.setValue("手机号不正确");
			} else {
				BackCode personalCode = list.get(0);
				if (personalCode.getCodetext() != null && code != null && personalCode.getCodetext().equals(code)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
					String date1 = df.format(new Date());// new Date()为获取当前系统时间
					String date2 = df.format(personalCode.getCreatedate());
					String str = getDistanceTime(date1, date2);
					if (Integer.parseInt(str) >= 5) {
						returnResult.setKey("error");
						returnResult.setValue("验证码过期请重新获取");
					} else {
						returnResult.setKey("success");
						returnResult.setValue("验证成功");
					}
				} else {
					returnResult.setKey("error");
					returnResult.setValue("验证码错误");
				}
			}
		}else{
			returnResult.setKey("error");
			returnResult.setValue("账号不正确");
		}

		return returnResult;
	}
	/**
	 * 
	 * @param page
	 * @param size
	 * @param type         //传  后台  或者  门店
	 * @param datestr      //全部    今天    本周    本月    本季度
	 * @param name         //名字
	 * @return
	 */
      public  Map<String, Object> 	queryLogsList(Integer page,Integer size,String type,String datestr,String name){
    	      Map<String,Object>  map=new HashMap<>();
        	  String sql="SELECT *  FROM  backlog  b WHERE 1=1 ";
        	  if(type!=null&&!type.equals("")){
    			  sql+=" and b.type='" + type + "' " ;
    	  }
        	  if(name!=null&&!name.equals("")){
      			sql+=" and b.name like '%"+name+"%'";
      		}
        	  if(datestr!=null&&!datestr.equals("")){
        		  if(datestr.equals("本季度")){
        			  sql+=" and QUARTER(b.operationdate)=QUARTER(now())";
        		  }else if(datestr.equals("本月")){
        			  sql+=" and  month(b.operationdate) = month(curdate()) and year(b.operationdate) = year(curdate())";
        		  }else if(datestr.equals("本周")){
        			  sql+=" and  month(b.operationdate) = month(curdate()) and week(b.operationdate) = week(curdate())";
        		  }else if(datestr.equals("今天")){
        			  sql+=" and DATEDIFF(b.operationdate,NOW())=0 ";
        		  }
        	  }
        	  sql+=" order by b.operationdate desc";
        	  if(page==null){
  				page=0;
  			  }
  			   if (size==null) {
  				size=10;
  			  }
	        	Query query = em.createNativeQuery(sql, BackLog.class);
	        	List<BackLog> enlist = (List<BackLog>) query.getResultList();
	  			map.put("totle", enlist.size());
	  			query.setFirstResult(page*size);
	  			query.setMaxResults(size);
	  			List<BackLog> result1 = query.getResultList();
	  			map.put("result", result1);
        	  return  map;
        	  
          }
	
	
	
  	@Transactional
  	public ReturnResult personalAccountSetting(String name, String email, String userid) {
  		ReturnResult returnResult = new ReturnResult();
  		BackUser operatorUser = backUserRepository.findOne(userid);
  		if (operatorUser != null) {
  			operatorUser.setName(name);
  			operatorUser.setEmail(email);
  			backUserRepository.save(operatorUser);
  			returnResult.setKey("success");
  			returnResult.setValue("修改成功");
  		} else {
  			returnResult.setKey("error");
  			returnResult.setValue("修改失败");
  		}
  		return returnResult;
  	}
	
	
  	public BackUser personalAccountSettinginfo(String userid) {
  		BackUser operatorUser = backUserRepository.findOne(userid);
		if (operatorUser != null) {
			if (operatorUser.getRole() != null) {
				BackRole backrole = backRoleRepository.findOne(operatorUser.getRole());
				operatorUser.setRole(backrole.getRolename());
			}
			return operatorUser;
		}
		return null;
	}

	@Transactional
	public ReturnResult personalAccountSettingPwd(String password, String userid) {
		ReturnResult returnResult = new ReturnResult();
		BackUser operatorUser = backUserRepository.findOne(userid);
		if (operatorUser != null) {
			operatorUser.setPassword(password);
			backUserRepository.save(operatorUser);
			returnResult.setKey("success");
			returnResult.setValue("修改成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("修改失败");
		}
		return returnResult;
	}
	
	
	
	
	
	

	/**
	 * 两个时间相差距离多少天多少小时多少分多少秒
	 * 
	 * @param str1
	 *            时间参数 1 格式：1990-01-01 12:00:00
	 * @param str2
	 *            时间参数 2 格式：2009-01-01 12:00:00
	 * @return String 返回值为：xx天xx小时xx分xx秒
	 */
	public static String getDistanceTime(String str1, String str2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date one;
		Date two;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return min + "";
	}
	
	
	// 获取6位随机数字
		public static String getSixCode() {
			// 数组，用于存放随机字符
			char[] chArr = new char[6];
			// 为了保证必须包含数字、大小写字母
			chArr[0] = (char) ('0' + StdRandom.uniform(0, 10));
			chArr[1] = (char) ('A' + StdRandom.uniform(0, 26));
			chArr[2] = (char) ('a' + StdRandom.uniform(0, 26));
			char[] codes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
					'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
					'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
					'z' };
			// charArr[3..len-1]随机生成codes中的字符
			for (int i = 3; i < 6; i++) {
				chArr[i] = codes[StdRandom.uniform(0, codes.length)];
			}

			// 将数组chArr随机排序
			for (int i = 0; i < 6; i++) {
				int r = i + StdRandom.uniform(6 - i);
				char temp = chArr[i];
				chArr[i] = chArr[r];
				chArr[r] = temp;
			}

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < chArr.length; i++) {
				sb.append(chArr[i]);
			}
			String s = sb.toString();

			return s;
		}
}
